package servlet;

import cn.hutool.json.JSONUtil;
import dao.OrderDAO;
import dao.UserDAO;
import dao.UserDAO1;
import entity.OrderViewItem;
import entity.User;
import vo.OrderView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: DataViewServlet
 * Package: servlet
 * Description:
 *
 * @Author LIEX
 * @create 2024/7/16 0:23
 * @Version 1.0
 */
@WebServlet(name = "orderView", value = "/order/view")
public class OrderViewServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        UserDAO1 userDAO1 = new UserDAO1();
        User user = userDAO1.findByName(username);

        OrderDAO orderDAO = new OrderDAO();
        List<Map.Entry<String, Integer>> top5Area;
        if("admin".equals(username)){
             top5Area = orderDAO.getTop4Area(null);
        }else{
            top5Area = orderDAO.getTop4Area(user.getId());
        }

        List<String> provinces = new ArrayList<>();
        List<OrderViewItem> orderViewItems = new ArrayList<>();

        int len = top5Area.size() > 4 ? 4 : top5Area.size();
        for(int i =0;i<len;i++){
            Map.Entry<String, Integer> entry = top5Area.get(i);
            provinces.add(entry.getKey());
            orderViewItems.add(new OrderViewItem(entry.getValue(),entry.getKey()));
        }

        String jsonStr = JSONUtil.toJsonStr(new OrderView(provinces,orderViewItems));
        System.out.println(jsonStr);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 获取PrintWriter对象
        PrintWriter out = resp.getWriter();
        out.print(jsonStr);
//        // 释放PrintWriter对象
        out.flush();
        out.close();
    }
}
